﻿#include "CBeltCtrMgr.h"
#include <QEventLoop>
#include <QTimer>
CBeltCtrMgr::CBeltCtrMgr(CBeltDataBase *pBeltData)
{
	m_pBeltData = pBeltData;
	m_pVlcCtrMange = nullptr;
	if (m_pVlcCtrMange == nullptr)
	{
		m_pVlcCtrMange = new CVlcCtrMange(pBeltData);
	}
	m_pMutex = new QMutex(QMutex::Recursive);
	m_bhread = false;
	m_pThread = new QThread();
	this->moveToThread(m_pThread);
	connect(m_pThread, SIGNAL(started()), this, SLOT(slot_threadWork()));
}



CBeltCtrMgr::~CBeltCtrMgr()
{
}

void CBeltCtrMgr::threadStart()
{
	m_pThread->start();
}

void CBeltCtrMgr::threadStop()
{
	m_bhread = false;
	m_pThread->quit();
	if (!m_pThread->wait(5000))
	{
		m_pThread->terminate();
	}
}

bool CBeltCtrMgr::ctrDevice(SCtrInfo & stCtrInfo)
{
	if (stCtrInfo.m_bCtrSync == true)
	{
		return ctrDev(stCtrInfo);
	}
	else
	{
		//如果线程没启动 开启线程
		if (!m_bhread)
			threadStart();
		if (m_pMutex->tryLock(3000))
		{
			if (m_vecCtrQueue.size() > 5)
				m_vecCtrQueue.clear();
			//如果是重复命令不添加
			if (m_vecCtrQueue.size() >= 1)
			{
				SCtrInfo stCtrInfoLast = m_vecCtrQueue[m_vecCtrQueue.size() - 1];
				if (stCtrInfo.m_enCtrCmd != stCtrInfoLast.m_enCtrCmd)
				{
					m_vecCtrQueue.push_back(stCtrInfo);
				}
			}
			else
			{
				m_vecCtrQueue.push_back(stCtrInfo);
			}
			m_pMutex->unlock();
			return true;
		}
		else
		{
			return false;
		}
	}
}

bool CBeltCtrMgr::ctrDev(SCtrInfo & stCtrInfo)
{
	ECCmdType enCmd = stCtrInfo.m_enCtrCmd;
	bool bResult = true;
	switch (enCmd)
	{
	case enCRun:
		m_pBeltData->m_bBeltWork = true;
		break;
	case enCStop:
		m_pBeltData->m_bBeltWork = false;
		break;
	case enCPlay:
		bResult = m_pVlcCtrMange->ctrDevice(stCtrInfo);;
		break;
	case enCStopPlay:
		bResult = m_pVlcCtrMange->ctrDevice(stCtrInfo);;
		break;
	default:
		bResult = true;
		break;
	}
	return bResult;
}
void CBeltCtrMgr::slot_threadWork()
{
	m_bhread = true;
	while (m_bhread)
	{
		m_pMutex->lock();
		if (m_vecCtrQueue.size() > 0)
		{
			SCtrInfo stCtrInfo = m_vecCtrQueue[0];
			m_vecCtrQueue.remove(0);
			m_pMutex->unlock();
			ctrDev(stCtrInfo);

		}
		else
		{
			m_pMutex->unlock();
		}
		QEventLoop loop;
		QTimer::singleShot(1000, &loop, SLOT(quit()));
		loop.exec();
	}
}
